package com.fwamgic.spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

/**
 * Java写Spark
 */
public class JavaWordCount {
    public static void main(String[] args) {
        //创建SparkConf
        SparkConf conf = new SparkConf().setAppName("JavaWordCount");

        //创建JavaSparkContext
        JavaSparkContext jsc = new JavaSparkContext(conf);

        //读取文件生成JavaRDD
        JavaRDD<String> lines = jsc.textFile(args[0]);

        //拍平操作
        JavaRDD<String> flated = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String line) throws Exception {
                return Arrays.asList(line.split("\\s")).iterator();
            }
        });

        //生成Tuple2
        JavaPairRDD<String, Integer> wordAndOne = flated.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String word) throws Exception {
                return Tuple2.apply(word, 1);
            }
        });

        //根据key进行聚合计数
        JavaPairRDD<String, Integer> reduced = wordAndOne.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer a, Integer b) throws Exception {
                return a + b;
            }
        });

        //交换Tuple2中的元素位置，方便根据计数结果排序
        JavaPairRDD<Integer, String> swapMapPair = reduced.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
            @Override
            public Tuple2<Integer, String> call(Tuple2<String, Integer> tp) throws Exception {
                return tp.swap();
            }
        });


        //对计数结果进行排序
        JavaPairRDD<Integer, String> sorted = swapMapPair.sortByKey(false);

        //再次调换Tuple2中元素的顺序
        JavaPairRDD<String, Integer> result = sorted.mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(Tuple2<Integer, String> tp) throws Exception {
                return tp.swap();
            }
        });

        //输出结果到文件中
        result.saveAsTextFile(args[1]);

        //关闭
        jsc.stop();
    }
}
